/**
 * Created by zhanglihe on 15/9/9.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'collection',
    'model',
    'dialog'
], function ($, common, ready, template, Collection, Model, dialog) {

    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.event();
            this.fetch();
        },

        fetch: function () {
            var that = this;
            that.collection = new Collection({
                container: 'data-list',
                template: 'data-item',
                url: _global.url.api + 'categorys',
                condition: {limit: 10, offset: 0, is_jd: 1},
                model: {
                    tag_name: 'tr',
                    url: {
                        put: _global.url.api + 'category/{id}'
                    },
                    event: {
                        '.item-edit:click': 'edit',
                        '.item-remove:click': 'remove',
                        '.item-add-sub:click': 'add_sub',
                        '.btn-show-pid:click': 'show_sub',
                        '.item-edit-sub:click': 'edit_sub'
                    },
                    add_sub: function (e) {
                        e.preventDefault();
                        that.data = {};
                        var _this = this;
                        dialog({
                            title: '添加子类',
                            width: 400,
                            content: template('add-sub-tpl', {parent: _this.data}),
                            ok: function () {
                                var refund_7days =0;
                                if($("input[name='return_7days']").is(":checked")){
                                    refund_7days =1
                                }
                                var data = {
                                    name: $('#name').val(),
                                    pid: $('#pid').val(),
                                    listorder: $('#listorder').val(),
                                    icon: that.data.icon,
                                    status: $('#status').val(),
                                    return_7days:refund_7days
                                };
                                if (!new Model({
                                        url: _global.url.api + 'category',
                                        data: data,
                                        valid_config: {
                                            name: 'required'
                                        }
                                    }).post()) {
                                    return false;
                                }
                                that.collection.reload();
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    edit: function (e) {
                        e.preventDefault();
                        that.data = this.data;
                        var _this = this;
                        dialog({
                            title: '编辑分类：' + _this.data.name,
                            width: 400,
                            content: template('edit-tpl', _this.data),
                            ok: function () {
                                _this.data.name = $('#name').val();
                                _this.data.listorder = $('#listorder').val();
                                _this.data.icon = that.data.icon;
                                if ($('input[name="status"]').is(':checked')) {
                                    _this.data.status = 1;
                                } else {
                                    _this.data.status = 0;
                                }
                                if ($('input[name="return_7days"]').is(':checked')) {
                                    _this.data.return_7days = 1;
                                } else {
                                    _this.data.return_7days = 0;
                                }
                                console.log(_this.data);
                                if ($('input[name="is_jd_show"]').is(':checked')) {
                                    _this.data.is_jd_show = 1;
                                } else {
                                    _this.data.is_jd_show = 0;
                                }
                                if (!_this.put()) {
                                    return false;
                                }
                                //that.collection.reload();
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    edit_sub: function (e) {
                        e.preventDefault();
                        that.data = this.data;
                        var _this = this;
                        parent_arr = that.collection.get_parents(_this.data.pid, _this.data.spid);
                        console.log('this.data', this.data);
                        dialog({
                            title: ' 编辑【' + ( _this.data.name ? _this.data.name : '父级') + '】分类信息',
                            width: 400,
                            content: template('edit-sub-tpl', {model: _this.data, parent_arr: parent_arr}),
                            ok: function () {
                                _this.data.icon = that.data.icon;
                                _this.data.name = $('#name').val();
                                _this.data.listorder = $('#listorder').val();
                                if ($('input[name="status"]').is(':checked')) {
                                    _this.data.status = 1;
                                } else {
                                    _this.data.status = 0;
                                }
                                if ($('input[name="is_jd_show"]').is(':checked')) {
                                    _this.data.is_jd_show = 1;
                                } else {
                                    _this.data.is_jd_show = 0;
                                }
                                if ($('input[name="return_7days"]').is(':checked')) {
                                    _this.data.return_7days = 1;
                                } else {
                                    _this.data.return_7days = 0;
                                }
                                if (!_this.put()) {
                                    return false;
                                }
                                //that.collection.reload();
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    show_sub: function (e) {
                        e.preventDefault();
                        var _this = this;
                        if (_this.data.pid_num > 0) {
                            $('#btn_show_pid_' + _this.data.id).hide();
                            $.ajax({
                                url: _global.url.api + 'categorys',
                                data: {pid: _this.data.id, is_jd: 1},
                                type: 'get',
                                async: false,
                                success: function (res) {
                                    if (res.code == 0) {
                                        item = res.data;
                                        for (var n in item) {
                                            that.collection.render_item(n, item[n]);
                                        }
                                    }
                                }
                            });
                        }
                    },
                    remove: function (e) {
                        e.preventDefault();
                        var _this = this;
                        dialog({
                            content: '确定要继续吗？',
                            ok: function () {
                                _this.data.action = 'del';

                                if (!_this.put()) {
                                    return false;
                                }
                                that.collection.reload();
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    valid_config: {
                        name: 'required'
                    }
                },
                render_item: function (key, item) {
                    $.extend(this.model, {
                        data: item,
                        template: this.template
                    });
                    this.models[item.id] = new Model(this.model);
                    this.models[item.id].create_element();
                    if (item.pid > 0) {
                        this.models[item.pid].el.after(this.models[item.id].el);
                    } else {
                        this.el.append(this.models[item.id].el);
                    }
                    /*for(var n in item.sub) {
                     this.render_item(n, item.sub[n]);
                     }*/
                },
                callback: function () {
                    loaded();
                },

                get_parents: function (pid, spid) {

                    var sub = [];

                    parent = that.collection.result.data[pid];

                    if (typeof(parent) !== 'undefined') {
                        if (parent['pid'] == 0) {  //顶级
                            $.each(that.collection.result.data, function () {
                                if (typeof(this['id']) !== 'undefined') {
                                    sub.push(this);
                                }
                            });
                        }
                    } else {
                        if (typeof(that.collection.result.data[spid]) !== 'undefined' && typeof(that.collection.result.data[spid]['sub']) !== 'undefined') {
                            top_parent = that.collection.result.data[spid]['sub'];
                            $.each(top_parent, function () {
                                if (typeof(this['id']) !== 'undefined') {
                                    sub.push(this);
                                }
                            });
                        }
                    }

                    return sub;
                }
            });
            this.collection.fetch();
        },

        event: function () {
            this.data = {};
            var _this = this;
            $('#coupon-add-tab').on('click', function (e) {
                e.preventDefault();
                dialog({
                    title: '添加大类',
                    width: 400,
                    content: template('add-tpl'),
                    ok: function () {
                        var refund_7days =0;
                        if($("input[name='returned_7days']").is(":checked")){
                            refund_7days =1
                        }
                        var data = {
                            name: $('#name').val(),
                            listorder: $('#listorder').val(),
                            status: $('#status').val(),
                            'refund_7days':refund_7days
                        };
                        if (!new Model({
                                url: _global.url.api + 'category',
                                data: data,
                                valid_config: {
                                    name: 'required'
                                }
                            }).post()) {
                            return false;
                        }
                        _this.fetch();
                    }, cancel: function () {
                    }
                }).show(e.target);
            });
            $('#update_jd_show_cate').on('click', function (e) {
                e.preventDefault();
                dialog({
                    title: '更新京东分类前端缓存',
                    content: '<div>更新完成后会提示ok,需要执行很长时间</div><a class="btn btn-default"  href="http://api.sixishop.com/update_jd_show_cate" target="_blank">点击链接更新</a>',
                    cancel: function () {
                    }
                }).show(e.target);
            });

            //上传图片
            $('body').on('click', '#btn-upload', function (e) {
                e.preventDefault();
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });
            $("#cate_goods").on("click",function(e){
                e.preventDefault();
                $("#data-list").hide();
                $(".cate_goods").show();
                var _this = this;
                _this.collection = new Collection({
                    container: 'data-lists',
                    template: 'datas-item',
                    url: _global.url.api + 'categorys_level',
                    condition: {limit: 15, offset: 0, is_jd: 1}
                });
                _this.collection.fetch();
            });
            $("#btn-search").on("click",function(e){
                e.preventDefault();
                _this.collection = new Collection({
                    container: 'data-lists',
                    template: 'datas-item',
                    url: _global.url.api + 'categorys_level',
                    condition: {limit: 15, offset: 0, is_jd: 1,keyword:$('input[name="keyword"]').val()}
                });
                _this.collection.fetch();
            });
        },
        imgPreview: function (img) {
            if (typeof img.id !== 'undefined') {
                this.data.icon = img.id;
                $('#img-view').html(template('img-tpl', img));
            }
        }
    };

    new index();

});